#!/usr/bin/env python
# coding: utf-8
"""
准备工作：需要把705upgrade目录放在脚本执行的路径下
"""

import re
import os
import time
import datetime
import string
from upgrade_software import *
#from onshs.ne.tnxxx.upgrade_software import * 

log_node_info = "upgrade_info"
log_node_fail = "upgrade_fail"
log_fail = "##### connect ne:%s failed.#####\n"
log_success = "##### upgrade ne:%s success.#####\n"
log_put_fail = "##### put ne:%s slot:%s file <%s> fail.#####\n"
log_put_success = "##### put ne:%s slot:%s file <%s> success.#####\n"

class TestCase(UpgradeSoftware):
    """
    TestCase
    """
    OPTIONS = [
        {
            'opt' : '--cfgfile',
            'dest': 'cfgfile',
            'metavar' : 'PATH',
            'help' : 'the file of netring configuration',
            'required' : False,
            'default' : "ip.txt"
        },     
    ]     
    
    def info_init(self):
        self.log_node_info = log_node_info
        self.log_node_fail = log_node_fail
        self.log_fail = log_fail 
        self.log_success = log_success
        self.log_put_fail = log_put_fail
        self.log_put_success = log_put_success
              
        return True 
    
    #以node为关键字，把信息保存到info_dic[node]中。
    def info_show(self, node, info):
        if not self.info_dic.has_key(node):
            self.info_dic[node] = ""
        self.info_dic[node] += info + '\n'        
        return True    
            
    def info_file_save(self, ip):
        path = self.work_path+'//'
        
        for node in self.info_dic:
            info_list = open(path+node+'_'+self.worktime+'.txt','a')            
            info_list.write(self.info_dic[node])
            info_list.close()
            
        return True
    
    def get_iplist(self):
        iplist_filted = []                
        if os.path.isfile(self.work_path+r'/'+ self.iplistfile):
            iplist = open(self.work_path+r'/'+ self.iplistfile)
            self.info_show(log_node_info, "The iplist file %s is existed."%(self.iplistfile)) 
        else:
            self.info_show(log_node_info, "The iplist file %s isn't existed."%(self.iplistfile))            
            return iplist_filted 
        
        for line in iplist:
            if re.match(r'^\s*$', line) is not None : continue # 忽略空白行
            if re.match(r'^\s*#', line) is not None : continue # 忽略注释行            
            iplist_filted.append(line.strip('\n'))        
            
        iplist.close()
        
        return iplist_filted  
       
    def _execute(self):        
        self.work_path = os.getcwd()
        self.info_init()
        
        worktime = str(datetime.datetime.now())
        self.worktime = worktime[:4]+worktime[5:7]+worktime[8:10]+'_'+worktime[11:13]+worktime[14:16]+worktime[17:19]
        self.iplistfile = self.options.cfgfile
        
        upgrade_file_dic = {
        "OPCA"  : [
        [r"/tffs/sys", r"tn705opca.img",         self.work_path+r'/705upgrade',        r"tn705opca.img"],            
        [r"/tffs/sys", r"mospec.dat",            self.work_path+r'/705upgrade',        r"mospec.dat"],
        [r"/tffs/sys", r"tbldata.dat",           self.work_path+r'/705upgrade',        r"tbldata.dat"],
        [r"/tffs/sys", r"tblspec.dat",           self.work_path+r'/705upgrade',        r"tblspec.dat"],
        [r"/tffs/sys", r"ZEBOS.CFG",             self.work_path+r'/705upgrade',        r"ZEBOS.CFG"],
        [r"/tffs/sys", r"snmpd.conf",            self.work_path+r'/705upgrade',        r"snmpd.conf"],
        [r"/tffs/sys", r"netring.ini",           self.work_path+r'/705upgrade',        r"netring.ini"],        
        [r"/tffs/sys", r"QTR6081V0.F([\da-f]+)", self.work_path+r'/705upgrade',        r"QTR6081V0.F([\da-f]+)"],            
        [r"/tffs/sys", r"QTR6082V0.F([\da-f]+)", self.work_path+r'/705upgrade',        r"QTR6082V0.F([\da-f]+)"],
        [r"/tffs/sys", r"QTR6082V1.F([\da-f]+)", self.work_path+r'/705upgrade',        r"QTR6082V1.F([\da-f]+)"],
        [r"/tffs/sys", r"qtr6083V0.F([\da-f]+)", self.work_path+r'/705upgrade',        r"qtr6083V0.F([\da-f]+)"],
        [r"/tffs/sys", r"tn705pos.img",          self.work_path+r'/705upgrade',        r"tn705pos.img"],
        [r"/tffs/sys", r"S6085G10.F([\da-f]+)",  self.work_path+r'/705upgrade',        r"S6085G10.F([\da-f]+)"],
        [r"/tffs/sys", r"S6085F16S.F([\da-f]+)", self.work_path+r'/705upgrade',        r"S6085F16S.F([\da-f]+)"],
        [r"/tffs/sys", r"S6085F1S.F([\da-f]+)",  self.work_path+r'/705upgrade',        r"S6085F1S.F([\da-f]+)"],
        [r"/tffs/sys", r"filelist.txt",          self.work_path+r'/705upgrade',        r"filelist.txt"],
        [r"/tffs/sys", r"upgrade.txt",           self.work_path+r'/705upgrade',        r"upgrade.txt"],
        ]          
        }
        
        self.info_dic = {}
        ip_list = self.get_iplist()         
        
        for ip in ip_list:
            upgrade_slot_dic = {"OPCA":     []   }
            self.set_ne_ip(0, ip)
            
            #get ne's two opca card's backup boot sys
            self.slot_backupsys_list=self.get_slot_backupsys_list(ip)
            
            #get ne's actual opca slot need to be upgraded, the first element is active opca,so ensure upgrade active opca first.
            if [] == self.slot_backupsys_list:
                continue
            for slot_backupsys in self.slot_backupsys_list:
                upgrade_slot_dic["OPCA"].append(slot_backupsys[0])
            
            #upgrade ne's opca slot.    
            if not self.upgrade_files(upgrade_file_dic, upgrade_slot_dic):
                return False
           
        worktime = str(datetime.datetime.now())
        self.worktime_end = worktime[:4]+worktime[5:7]+worktime[8:10]+'_'+worktime[11:13]+worktime[14:16]+worktime[17:19]
        
        self.info_show(log_node_info, "The upgrade file operation begin time %s "%(self.worktime))
        self.info_show(log_node_info, "The upgrade file operation end time %s "%(self.worktime_end))
        
        ip = '0.0.0.0'
        self.info_file_save(ip) 
        return True
    
if __name__ == "__main__" :
    case = TestCase()
    case.execute()